package com.hzit.manager.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


import com.hzit.manager.valid.AddGroup;
import com.hzit.manager.valid.UpdateGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.hzit.manager.entity.BrandEntity;
import com.hzit.manager.service.BrandService;
import com.hzit.common.utils.PageUtils;
import com.hzit.common.utils.R;

import javax.validation.Valid;


/**
 * @author hbxfwf
 * @email 2568783935@gmail.com
 * @date 2023-06-06 15:58:41
 */
@RestController
@RequestMapping(value = "manager/brand")
public class BrandController {
	@Autowired
	private BrandService brandService;

	/**
	 * 列表
	 */

	@GetMapping("/list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = brandService.queryPage(params);

		return R.ok().put("page", page);
	}

	@GetMapping("/findAll")
	public R findAll() {
		//1. 查询所有品牌
		List<BrandEntity> list = brandService.list();
		//2. 处理name字段名字为text
		List<Map> list1 = list.stream().map(m -> {
			Map map = new HashMap<>();
			map.put("id", m.getId());
			map.put("text", m.getName());
			return map;
		}).collect(Collectors.toList());
		return R.ok().put("list", list1);
	}

	/**
	 * 信息
	 */
	@GetMapping("/info/{id}")
	public R info(@PathVariable("id") String id) {
		BrandEntity brand = brandService.getById(id);

		return R.ok().put("brand", brand);
	}

	/**
	 * 保存
	 */
	@PostMapping("/save")
	// public R save(@Valid @RequestBody BrandEntity brand) {
	public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand) {
		// if (result.hasErrors()) {
		// 	List<FieldError> fieldErrors = result.getFieldErrors();
		// 	Map map = new HashMap();
		// 	for (FieldError error : fieldErrors) {
		// 		map.put(error.getField(),error.getDefaultMessage());  // key：字段名 value：字段错误信息
		// 	}
		// 	return  R.error().put("errors",map);
		//
		// }
		brandService.save(brand);

		return R.ok();
	}

	/**
	 * 修改
	 */
	@PutMapping("/update")
	public R update(@Validated(UpdateGroup.class)@RequestBody BrandEntity brand) {
		brandService.updateById(brand);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@DeleteMapping("/delete")
	public R delete(@RequestBody String[] ids) {
		brandService.removeByIds(Arrays.asList(ids));

		return R.ok();
	}

	//添加品牌同时添加订单
	@PostMapping("/saveBrandAndOrder")
	public R saveBrandAndOrder(){
		brandService.saveBrandAndOrder();
		return R.ok();
	}
}
